package com.shcz.migu.utils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

import com.soundcloud.android.crop.Crop;

import java.io.File;
import java.util.Date;

/**
 * Created by levin on 2015/12/31.
 */
public class PhotoController {

    private Activity mActivity;
    public final int BY_ALBUM     = 10101;
    public final int BY_CAMERA    = 10102;
    public final int CROP_PICTURE = 10103;

    private String tempImagefilePath = "";
    private String cropImagefilePath = "";
    private Uri imageUri;
    private Bitmap mResultBitmap = null;

    private Handler handler = new Handler();

    private boolean isCrop = false;

    private boolean isWithAspect = false;

    public boolean isWithAspect() {
        return isWithAspect;
    }

    public void setWithAspect(boolean withAspect) {
        isWithAspect = withAspect;
    }

    public void setCrop(boolean isCrop) {
        this.isCrop = isCrop;
    }

    public boolean isCrop() {
        return isCrop;
    }

    public void setTempImagefilePath(String tempImagefilePath) {
        this.tempImagefilePath = tempImagefilePath;
    }

    public void setCropImagefilePath(String cropImagefilePath) {
        this.cropImagefilePath = cropImagefilePath;
    }

    public String getTempImagefilePath() {
        return tempImagefilePath;
    }

    public String getCropImagefilePath() {
        return cropImagefilePath;
    }

    public PhotoController(Activity activity) {
        mActivity = activity;
    }

    public void getPhotoFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        mActivity.startActivityForResult(intent, BY_ALBUM);
    }

    public void getPhotoFromCamera() {
        tempImagefilePath = CommonUtils.getAppDirPath() + new Date().getTime() + "camera.dest.jpg";
        File file = new File(tempImagefilePath);
        if (!file.exists()) {
            PathUtil.createnNewFile(tempImagefilePath);
        }
//        imageUri = Uri.fromFile(file);
        imageUri = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".provider", file);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        mActivity.startActivityForResult(intent, BY_CAMERA);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 打开相册
                case BY_ALBUM:
                    tempImagefilePath = returnGalleryPic(intent, mActivity);
                    getPhotoOver();
                    break;
                // 拍照
                case BY_CAMERA:
                    getPhotoOver();
                    break;
                case CROP_PICTURE:
                    dealPicture(intent);
                    break;
                case Crop.REQUEST_CROP:
                    handleCrop(resultCode, intent);
                    break;
            }
        }
    }


    private void beginCrop(Uri source) {
        Uri destination = Uri.fromFile(new File(CommonUtils.getAppDirPath() + new Date().getTime() + ".jpg"));
        if(isWithAspect){
            Crop.of(source, destination).withAspect(20,11).start(mActivity);
        }else{
            Crop.of(source, destination).asSquare().start(mActivity);
        }

        //		overridePendingTransition(0,0);
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            String path = Crop.getOutput(result).getPath();
            Log.d("image", "path = " + path);
            if (photoControllerListener != null)
                photoControllerListener.onGetPhoto(path);
        } else if (resultCode == Crop.RESULT_ERROR) {
            CommonToast.showToast(Crop.getError(result).getMessage());
        }
    }

    private void dealPicture(Intent intent) {
        Uri uri = intent.getData();
        if (TextUtils.isEmpty(cropImagefilePath) && uri != null) {
            String path = uri.getPath();
            cropImagefilePath = path;
        }
        File file = PathUtil.createnNewFile(cropImagefilePath);
        try {
            Log.d("image", "dealPicture cropImagefilePath = " + cropImagefilePath + " tempImagefilePath =" + tempImagefilePath);
            imageUri = Uri.parse("file://" + cropImagefilePath);
            mResultBitmap = BitmapUtil.reviewPicRotate(mResultBitmap, cropImagefilePath);
            mResultBitmap = BitmapUtil.decodeUriAsBitmap(mActivity, imageUri);
            PathUtil.saveMyBitmap(file, mResultBitmap);
        } catch (Exception e) {
            mResultBitmap = null;
            System.gc();
        }
        if (photoControllerListener != null)
            photoControllerListener.onGetPhoto(cropImagefilePath);
    }

    private void getPhotoOver() {
        if (isCrop) {
            cropImagefilePath = tempImagefilePath;
            Log.d("image", "getPhotoOver cropImagefilePath = " + cropImagefilePath);
            if (TextUtils.isEmpty(cropImagefilePath)) {
                return;
            }
            final File oldpic = new File(cropImagefilePath);
            imageUri = Uri.fromFile(oldpic);
            beginCrop(imageUri);
        } else {
            if (photoControllerListener != null)
                photoControllerListener.onGetPhoto(tempImagefilePath);
//            new Thread() {
//
//                @Override
//                public void run() {
//                    super.run();
//                    tempImagefilePath = BitmapUtil.createScaledImage(tempImagefilePath, 0);  //裁剪图片并返回图片地址
//                    Log.d("image", "getPhotoOver tempImagefilePath = " + tempImagefilePath);
//
//                    handler.post(new Runnable() {
//                        public void run() {
//                            if (photoControllerListener != null)
//                                photoControllerListener.onGetPhoto(tempImagefilePath);
//                        }
//                    });
//                }
//            }.start();
        }
    }

    private String returnGalleryPic(Intent data, Activity context) {
        if (data != null) {
            Uri originalUri = data.getData();
            if (originalUri.toString().startsWith("content://")) {
                String[] proj = {MediaStore.Images.Media.DATA};
                @SuppressWarnings("deprecation")
                Cursor actualimagecursor = context.managedQuery(originalUri, proj, null, null, null);
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                String img_path = actualimagecursor.getString(actual_image_column_index);
                return img_path;
            } else {
                String lastpath = originalUri.toString().replace("file://", "");
                return lastpath;
            }
        } else {
            return null;
        }
    }


    public void cropImageUriFromCamera(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        mActivity.startActivityForResult(intent, CROP_PICTURE);
    }

    private PhotoControllerListener photoControllerListener;

    public void setPhotoControllerListener(PhotoControllerListener photoControllerListener) {
        this.photoControllerListener = photoControllerListener;
    }

    public interface PhotoControllerListener {
        void onGetPhoto(String path);
    }
}
